﻿using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using UnityEngine;
namespace Share
{
    public static class XKLog
    {
        static bool saveStackTrace = false;
        static bool sendStackTrace = false;
        static string saveStackTraceFile = "";
        public static bool AutoCreateLogDir { get; set; } = true; // 控制是否自动创建日志目录

        private static string GetLogFilePath()
        {
            string t = DateTime.Now.ToString("yyyy-MM-dd_HH-mm-ss");
            string baseDir = Path.GetDirectoryName(Application.dataPath);

            if (Application.isEditor)
            {
                // 编辑器模式下，Logs目录与Assets同级
                baseDir = Path.GetDirectoryName(baseDir);
            }
            // 发布版本下，Logs目录与exe同级(baseDir保持不变)

            string logDir = Path.Combine(baseDir, "Logs");

            try
            {
                if (AutoCreateLogDir && !Directory.Exists(logDir))
                {
                    Directory.CreateDirectory(logDir);
                }
                return Path.Combine(logDir, $"StackTrackLog_{t}.txt");
            }
            catch (Exception ex)
            {
                Debug.LogError($"创建日志目录失败: {ex.Message}");
                return Path.Combine(baseDir, $"StackTrackLog_{t}.txt");
            }
        }

        public static void DoStart(bool bEnable, bool sendEnable)
        {
            saveStackTrace = bEnable;
            sendStackTrace = sendEnable;
            saveStackTraceFile = GetLogFilePath();

            Debug.Log($"日志文件保存路径: {saveStackTraceFile}");
            Debug.Log($"当前平台: {Application.platform}");
        }

        public static void SaveStackTrace(string text)
        {
            if (sendStackTrace)
                UDPSender.Instance.SendData(text);
            m_LogError.Add(text);
            var cmd = new EventParamCommon();
            cmd.AddData<string>("Value", text);
            EventMgr.Instance.TriggerEvent((int)SystemEventDef.System_LogError, cmd);

            if (!saveStackTrace)
                return;

            try
            {
                if (string.IsNullOrEmpty(saveStackTraceFile))
                {
                    saveStackTraceFile = GetLogFilePath();
                }

                // 使用using确保资源释放
                using (FileStream stream = new FileStream(saveStackTraceFile, FileMode.Append, FileAccess.Write))
                using (StreamWriter writer = new StreamWriter(stream))
                {
                    string timestamp = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                    writer.WriteLine($"{timestamp}:{text}");
                }
            }
            catch (Exception ex)
            {
                Debug.LogError($"保存日志失败: {ex.Message}");
            }
        }
        [System.Diagnostics.Conditional("ENABLE_LOG")]
        public static void Log(string format, params object[] args)
        {
            if (args.Length < 1)
            {
                Debug.Log(format);
            }
            else
            {
                Debug.LogFormat(format, args);
            }
        }


        [System.Diagnostics.Conditional("ENABLE_LOG")]
        public static void LogWarning(object message, UnityEngine.Object context)
        {
            Debug.LogWarning(message, context);
        }
        [System.Diagnostics.Conditional("ENABLE_LOG")]
        public static void LogWarning(object message)
        {
            Debug.LogWarning(message);
        }
        [System.Diagnostics.Conditional("ENABLE_LOG")]
        public static void LogWarning(UnityEngine.Object context, string format, params object[] args)
        {
            Debug.LogWarningFormat(context, format, args);
        }

        [System.Diagnostics.Conditional("ENABLE_LOG")]
        public static void LogWarning(string format, params object[] args)
        {
            if (args.Length < 1)
            {
                Debug.LogWarning(format);
            }
            else
            {
                Debug.LogWarningFormat(format, args);
            }
        }

        public static void LogError(object message)
        {
            Debug.LogError(message);
            SaveStackTrace(message.ToString());
        }

        public static void LogError(object message, UnityEngine.Object context)
        {
            Debug.LogError(message, context);
            SaveStackTrace(message.ToString());
        }

        public static void LogError(string format, params object[] args)
        {
            if (args.Length < 1)
            {
                Debug.LogError(format);
                SaveStackTrace(format);
            }
            else
            {
                Debug.LogErrorFormat(format, args);
                SaveStackTrace(string.Format(format, args));
            }
        }

        public static void LogError(UnityEngine.Object context, string format, params object[] args)
        {
            Debug.LogErrorFormat(context, format, args);
            SaveStackTrace(string.Format(format, args));
        }

        public static void LogThrow(object message)
        {
            throw new Exception(message.ToString());
        }

        public static void LogJson(string str)
        {
            string formattedJson = JsonConvert.SerializeObject(
                JsonConvert.DeserializeObject(str),
                Formatting.Indented
            );
            XKLog.LogError(formattedJson);
        }



        static List<string> m_LogError = new List<string>();

        public static string LogErrorString(int index)
        {
            return m_LogError[index];
        }
        public static int LogErrorCount()
        {
            return m_LogError.Count;
        }
        public static void ClearLogError()
        {
            m_LogError.Clear();
        }
    }

}
